import jwt
import time
from datetime import datetime, timedelta

# JwtToken工具类
class TokenUtil:
    UserKey = "FANYINGQ"
        
    # 生成token
    @staticmethod
    def encode(payload):
        jwt_encode = jwt.encode(payload=payload,key=TokenUtil.UserKey,algorithm='HS512')
        return jwt_encode
 
    # 解密token
    @staticmethod
    def decode(token):
        if token is not None:
            jwt_decode = jwt.decode(token,key=TokenUtil.UserKey, algorithms=['HS512'],verify=False)
            return jwt_decode
        else:
            return ''

    # 获取密钥
    @staticmethod
    def getSecretKey():
        return TokenUtil.UserKey
    
    # 获取会员ID
    @staticmethod
    def getMemberId(token):
        if token is not None:
            jwt_decode = jwt.decode(token,key=TokenUtil.UserKey, algorithms=['HS512'],verify=False)
            return jwt_decode['userId']
        else:
            return ''

    # 获取Payload
    @staticmethod
    def getPayload(memberid, phone):
        # 获取当前时间
        now = datetime.now()

        # 计算一年后的时间
        one_year_later = now + timedelta(days=365)

        # 转换为时间戳
        one_year_later_timestamp = one_year_later.timestamp()

        payload = {}
        payload['sub'] = memberid
        payload['exp'] = one_year_later_timestamp
        payload['userId'] = memberid
        payload['iat'] = now.timestamp()
        payload['account'] = phone
        payload['userKey'] = TokenUtil.UserKey
        
        return payload
